<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;
class CoUser extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    private $select = ['id','nickname','avatar','mobile','gender','truename','is_type','is_shen','school_id','api_token','status'];

    protected $table = 'co_user';


    public function getuser($token){
        return self::where("api_token", $token)->select('id','nickname','avatar','mobile','gender','truename','is_type','is_shen','school_id','api_token','status','openid','order_num','avatarUrl','tel','balance','type')->first();
    }

    /**
     * 修改用户余额
     * @param $user_id 用户ID
     * @param $money 金额
     * @param int $type 类型 收入 2惩罚 3提现
     */
    public function save_user($user_id,$money,$type=1,$remark=''){
        $user = self::where('id',$user_id)->first();
        if($user){
//            DB::beginTransaction();
            //判断类型
            if($type ==1){
                if(empty($remark)){
                    $remark = '收入金额：+'.$money;
                }
                $user->balance = $user->balance+$money;
            }elseif ($type ==2){
                if(empty($remark)){
                    $remark = '处罚金额：-'.$money;
                }
                $user->balance = $user->balance-$money;
            }else{
                if(empty($remark)){
                    $remark = '提现金额：-'.$money;
                }
                $user->balance = $user->balance-$money;
            }
            $res = $user->save();
            if($res == false){
//                DB::rollBack();
                return false;
            }
            $CoUserBalanceLog = new CoUserBalanceLog();
            $CoUserBalanceLog->user_id = $user_id;
            $CoUserBalanceLog->money = $money;
            $CoUserBalanceLog->type = $type;
            $CoUserBalanceLog->remark = $remark;
            $res = $CoUserBalanceLog->save();
            if($res == false){
//                DB::rollBack();
                return false;
            }
//            DB::commit();
            return true;
        }else{
            return false;
        }
    }


    /**
     * 增加取消次数
     * @param $user_id
     * @param int $num
     * @return bool
     */
    public function save_order_num($user_id,$num=1){
        $user = self::where('id',$user_id)->first();
        if(empty($user)){
            return false;
        }else{
            $user->order_num = $user->order_num +1;
            $res = $user->save();
            if($res == false){
                return false;
            }
            return true;
        }
    }

}
